<template>
    <div class="select-map">
        <baidu-map 
            :center="center" 
            :zoom="zoom" 
            :map-click="false" 
            style="width: 100%;height:250px;"
            @mousemove="syncPolygon" 
            @ready="handler"
            @click="paintPolygon" 
            @rightclick="newPolygon">
            <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-map-type>
            <bm-polygon 
                :path="path" 
                v-for="(path,index) of polygonPath.paths" 
                :key="index" 
                stroke-color="blue"
                fill-color="red" 
                :fill-opacity="0.8" 
                :stroke-opacity="0.5" 
                :stroke-weight="2"/>
        </baidu-map>
        <div class="block-wrap" v-if="polygonPath.paths.length">
            <el-tag class="block-item" v-for="(item, index) in polygonPath.paths" :key="index" closable @click="focusBlock(item)" @close="deleteBlock(index)">
                区域{{ index + 1 }}
            </el-tag>
        </div>
        <div class="box-wrap">
            <el-button type="success" @click="openMap">选择区域</el-button>
        </div>
        <div class="pop-overlay" v-show="show">
            <div class="map-box">
                <div class="map-title">
                    {{ title }}
                    <div class="btn-wrap">
                        <i class="el-icon-circle-close" @click="closeMap"></i>
                    </div>
                </div>
                <div class="map-wrap">
                    <baidu-map 
                        :center="center" 
                        :zoom="zoom" 
                        :map-click="false" 
                        style="width: 100%;height:100%;"
                        @mousemove="syncPolygon" 
                        @ready="handler"
                        @click="paintPolygon" 
                        @rightclick="newPolygon">
                        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                        <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-map-type>
                        <bm-control :offset="{top: 10, left: 10}">
                            <el-autocomplete
                                v-model="address"
                                clearable
                                :trigger-on-focus="false"
                                :fetch-suggestions="querySearchAsync"
                                placeholder="输入地址快速检索"
                                @select="handleSelect"
                                style="width:350px;margin:10px;">
                                <template slot-scope="{ item }">
                                    <div class="name">{{ item.title }}</div>
                                    <span class="addr" style="font-size:12px;color:#999;">{{ item.address }}</span>
                                </template>
                            </el-autocomplete>
                            <el-button type="primary" @click="toggle('polygonPath')">{{ polygonPath.editing ? '停止绘制' : '开始绘制' }}</el-button>
                        </bm-control>
                        <bm-polygon 
                            :path="path" 
                            v-for="(path,index) of polygonPath.paths" 
                            :key="index" 
                            stroke-color="blue"
                            fill-color="red" 
                            :fill-opacity="0.8" 
                            :stroke-opacity="0.5" 
                            :stroke-weight="2">删除</bm-polygon>
                    </baidu-map>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'drawMap',
        props: {
            value: {
                type: Array,
                default() {
                    return []
                }
            }
        },
        components: {},
        data() {
            return {
                title: '绘制区域',
                show: false,
                address: '',
                center: {
                    lng: 116.40,
                    lat: 39.90
                },
                zoom: 10,
                polygonPath: {
                    editing: false,
                    paths: [] // 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
                },
                BMap: null,
                map: null,
            }
        },
        watch: {
            value: {
                handler: function(val) {
                    console.log(val)
                    this.polygonPath.paths = [...val];
                    if(val.length) {
                        let block = val[0];
                        if(block.length) {
                            this.center.lng = block[0].lng;
                            this.center.lat = block[0].lat;
                        }
                    }
                },
                immediate: true
            }
        },
        methods: {
            openMap() {
                this.show = true;
            },
            closeMap() {
                this.show = false;
                console.log(this.polygonPath.paths, 'this.polygonPath.paths')
                this.$emit('input', this.polygonPath.paths)
            },
            handler({ BMap, map }) {
                this.BMap = BMap;
                this.map = map;
                let _this = this; // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
				// var geolocation = new BMap.Geolocation();
				// geolocation.getCurrentPosition(function(r){
				// 	_this.center = {lng: r.longitude, lat: r.latitude}; // 设置center属性值
                // },{enableHighAccuracy: true});
                map.enableScrollWheelZoom(true)
            },
            // 开启多边形绘制
            toggle(name) {
                this[name].editing = !this[name].editing
                if(this[name].editing) {
                    this.polygonPath.paths.push([])
                }
                // 在这里做一步判断，如果有路径且开启绘制就把原来的路径清空
                // if (this.polygonPath.paths && this.polygonPath.editing) {
                //     this.polygonPath.paths = []
                // }
            },
            // 鼠标移动时
            syncPolygon(e) {
                if (!this.polygonPath.editing) {
                    return
                }
                const {
                    paths
                } = this.polygonPath
                if (!paths.length) {
                    return
                }
                const path = paths[paths.length - 1]
                if (!path.length) {
                    return
                }
                if (path.length === 1) {
                    path.push(e.point)
                }
                this.$set(path, path.length - 1, e.point)
            },
            // 鼠标右键多边形绘制完成
            newPolygon(e) {
                if (!this.polygonPath.editing) {
                    return
                }
                // 当开始绘制后把按钮调回开始绘制状态，防止绘制多个图形
                this['polygonPath'].editing = !this['polygonPath'].editing
                const {
                    paths
                } = this.polygonPath
                if (!paths.length) {
                    paths.push([])
                }
                const path = paths[paths.length - 1]
                path.pop()
                // if (path.length) {
                //     paths.push([])
                // }
            },
            // 鼠标左键点击时往路径里push一个点
            paintPolygon(e) {
                if (!this.polygonPath.editing) {
                    return
                }
                const {
                    paths
                } = this.polygonPath; 
                !paths.length && paths.push([])
                paths[paths.length - 1].push(e.point)
            },
            querySearchAsync(queryString, callback) {
                if(this.BMap) {
                    var local = new this.BMap.LocalSearch(this.map, {
                        renderOptions:{
                            map: this.map
                        },
                        onSearchComplete: function(results) {
                            let resultArr = [];
                            for (var i = 0; i < results.getCurrentNumPois(); i++) {
                                resultArr.push(results.getPoi(i));
                            }
                            callback(resultArr);
                        }
                    });
                    local.search(queryString);
                }
            },
            handleSelect(item) {
                this.center = item.point;
                this.address = item.title;
            },
            deleteBlock(index) { // 删除区域
                this.polygonPath.paths.splice(index, 1);
                this.$emit('input', this.polygonPath.paths)
            },
            focusBlock(item) { // 聚焦到区域位置
                if(item.length) {
                    this.center.lng = item[0].lng;
                    this.center.lat = item[0].lat;
                }
            },
        }
    }
</script>

<style lang="scss" scoped>
.select-map {
    .pop-overlay {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 2000;
        overflow: hidden;
        background-color: rgba(0, 0, 0, .3);
        padding: 5% 10%;
        .map-box {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            background: #fff;
            .map-title {
                padding: 10px 10px 0;
                line-height: 30px;
                font-size: 16px;
                font-weight: 700;
                .btn-wrap {
                    float: right;
                    font-size: 24px;
                    cursor: pointer;
                }
            }
            .map-wrap {
                flex: 1;
                padding: 10px;
                overflow: hidden;
            }
        }
    }

    .block-wrap {
        .block-item {
            cursor: pointer;
            margin: 10px 10px 0 0;
        }
    }
    .box-wrap {
        margin-top: 10px;
    }
}
</style>
